package com.lv.leyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lv.leyou.dto.SpecGroupDTO;
import com.lv.leyou.dto.SpecParamDTO;
import com.lv.leyou.entity.SpecGroup;
import com.lv.leyou.entity.SpecParam;
import com.lv.leyou.mapper.SpecGroupMapper;
import com.lv.leyou.service.SpecGroupService;
import com.lv.leyou.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

    @Autowired
    private SpecParamService specParamService;
    @Override
    public List<SpecGroupDTO> querySpecGroupByCategoryId(Long id) {
        List<SpecGroup> list = query().eq("category_id", id).list();
        List<SpecGroupDTO> specGroupDTOS = SpecGroupDTO.convertEntityList(list);
        return specGroupDTOS;
    }
    @Transactional
    @Override
    //新增规格组
    public void saveSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        save(specGroup);
    }
    @Transactional
    @Override
    //修改规格组
    public void updateSpecGroup(SpecGroupDTO specGroupDTO) {
        SpecGroup specGroup = specGroupDTO.toEntity(SpecGroup.class);
        updateById(specGroup);
    }

    @Override
    public List<SpecGroupDTO> querySpecGroupAndSpecParamByCategoryId(Long categoryId) {
        //先根据分类id查询规格组的信息
        List<SpecGroup> specGroupList = query().eq("category_id", categoryId).list();
        //再根据分类id查询规格参数
        List<SpecParam> specParmList = specParamService.query().eq("category_id", categoryId).list();
        List<SpecParamDTO> list1 = SpecParamDTO.convertEntityList(specParmList);
        //对规格参数分组，groupid一致的放在一组,long 存放的是分组的id
        Map<Long, List<SpecParamDTO>> map = list1.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        //封装到SpecGroupDTO中
        List<SpecGroupDTO> specGroupDTOList = SpecGroupDTO.convertEntityList(specGroupList);
        for (SpecGroupDTO specGroupDTO : specGroupDTOList) {
            //通过key获得value，也就是规格组的id
            List<SpecParamDTO> specParamDTOS = map.get(specGroupDTO.getId());
            specGroupDTO.setParams(specParamDTOS);
        }
        return specGroupDTOList;
    }
}
